<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card>
      <!-- 警告区域 -->
       <el-alert title="只允许为三级商品属性添加参数！" :closable="false" type="warning"></el-alert>

       <!-- 级联选择器区域 -->
       <div class="cate_opt">
         <span>请选择参数分类：</span>
          <el-cascader
          v-model="selectCateKeys"
          :options="cateList"
          :props="CateProps"
          @change="handleChange"
          size="medium ">
          </el-cascader>
       </div>
       <!-- tabs 页标签 -->
       <el-tabs v-model="activeName" @tab-click="handleCateClick">
         <!-- 动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isBtnDisabled" @click="showAddParamsDialog">添加动态参数</el-button>

          <!-- 动态参数表格 -->
          <el-table
            :data="manyParamsData"
            border
            stripe
            style="width: 100%">
            <!-- 下拉列表 -->
            <el-table-column type="expand" >
              <template v-slot="slotProps">
                <el-tag v-for="(item, i) in slotProps.row.attr_vals" :key="i" closable @close="deleteTag(slotProps.row, i)">{{ item }}</el-tag>
                <el-input
                class="input-new-tag"
                v-if="slotProps.row.inputVisible"
                v-model="slotProps.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(slotProps.row)"
                @blur="handleInputConfirm(slotProps.row)"
              >
              </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="showInput(slotProps.row)">+ New Tag</el-button>

              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template v-slot="slotProps">
                <el-button type="primary" class="el-icon-edit" size="mini" @click="showEditParamsDialog(slotProps.row.attr_id)">编辑</el-button>
                <el-button type="danger" class="el-icon-delete" size="mini" @click="removeParams(slotProps.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>

          </el-table>
        </el-tab-pane>
        <!-- 静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="isBtnDisabled" @click="showAddParamsDialog">添加静态属性</el-button>

          <!-- 静态属性表格 -->
          <el-table
            :data="onlyParamsData"
            border
            stripe
            style="width: 100%">
            <!-- 下拉列表 -->
            <el-table-column type="expand" >
              <template v-slot="slotProps">
                <el-tag v-for="(item, i) in slotProps.row.attr_vals" :key="i" closable @close="deleteTag(slotProps.row, i)">{{ item }}</el-tag>
                <el-input
                class="input-new-tag"
                v-if="slotProps.row.inputVisible"
                v-model="slotProps.row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(slotProps.row)"
                @blur="handleInputConfirm(slotProps.row)"
              >
              </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="showInput(slotProps.row)">+ New Tag</el-button>

              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template v-slot="slotProps">
                <el-button type="primary" class="el-icon-edit" size="mini" @click="showEditParamsDialog(slotProps.row.attr_id)">编辑</el-button>
                <el-button type="danger" class="el-icon-delete" size="mini" @click="removeParams(slotProps.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>

          </el-table>
        </el-tab-pane>
        </el-tabs>
    </el-card>
    <!-- 添加参数会话框 -->
    <el-dialog
          :title="'添加' + titleText"
          :visible.sync="addParamsDialogVisible"
          width="50%"
           @close="addParamsDialogVisibleClosed">

          <!-- 表单区域 -->
        <el-form :model="addParamsForm" :rules="addParamsFormrules" ref="addParamsFormRef" label-width="100px" class="demo-ruleForm">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="addParamsForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数会话框 -->
     <el-dialog
          :title="'修改' + titleText"
          :visible.sync="editParamsDialogVisible"
          width="50%"
          @close="editParamsDialogVisibleClosed">

          <!-- 表单区域 -->
        <el-form :model="editParamsForm" :rules="editParamsFormrules" ref="editParamsFormRef" label-width="100px" class="demo-ruleForm">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="editParamsForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      selectCateKeys: [], // 级联选择器 选中的id 数组
      cateList: [], // 商品分类列表
      CateProps: { // 级联选择器，选项显示规则
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name'
      },
      activeName: 'many', // 控制 tabs 页标签默认展示页
      manyParamsData: [], // 动态参数表格数据
      onlyParamsData: [], // 静态属性参数表格数据
      addParamsDialogVisible: false, //  控制添加参数会话框的显示或隐藏
      editParamsDialogVisible: false, // 控制修改参数会话框的显示或隐藏
      addParamsForm: { // 添加参数数据对象
        attr_name: '',
        attr_sel: ''
      },
      editParamsForm: { // 修改参数数据对象
        attr_name: '',
        attr_sel: '',
        attr_id: ''
      },
      addParamsFormrules: { // 添加参数验证规则
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      editParamsFormrules: { // 修改参数验证规则
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    handleChange () { // 级联选择器选中发生变化时的函数
      if (this.selectCateKeys.length < 3) {
        this.selectCateKeys = []
        this.manyParamsData = []
        this.onlyParamsData = []
        return
      }
      this.getParamsData()
    },
    async getCateList () { // 获取全部商品分类
      const { data: res } = await this.$http.get('categories')
      console.log(res)
      if (res.meta.status !== 200) return this.$msg.error('获取参数失败！')
      this.cateList = res.data
    },
    handleCateClick () { // tabs 标签页切换时触发的函数
      this.getParamsData()
    },
    async getParamsData () { // 获取动态属性和静态参数的函数
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: {
          sel: this.activeName
        }
      })
      if (res.meta.status !== 200) return
      res.data.forEach(item => {
        if (item.attr_vals) {
          item.attr_vals = item.attr_vals.split(' ')
        } else {
          item.attr_vals = []
        }
        item.inputValue = '' // 下拉列表中input 的值
        item.inputVisible = false // 控制下拉列表中的input的显示或隐藏
      })
      if (this.activeName === 'many') {
        this.manyParamsData = res.data
      } else {
        this.onlyParamsData = res.data
      }
      console.log(res.data)
    },
    showAddParamsDialog () { // 点击添加动态参数和静态属性按钮触发
      this.addParamsDialogVisible = true
    },
    addParamsDialogVisibleClosed () { // 添加参数会话框关闭，重置表单
      this.$refs.addParamsFormRef.resetFields()
    },
    addParams () { // 添加动态参数或静态属性
      this.$refs.addParamsFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$msg.error('添加失败！')
        this.$msg.success('添加成功')
        this.getParamsData()
        this.addParamsDialogVisible = false
      })
    },
    async showEditParamsDialog (id) { // 点击编辑按钮触发
      this.editParamsForm.attr_id = id
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${id}`, { params: { attr_sel: this.activeName } })
      if (res.meta.status !== 200) return
      this.editParamsForm.attr_name = res.data.attr_name
      this.editParamsDialogVisible = true
    },
    editParamsDialogVisibleClosed () { // 修改参数会话框关闭，重置表单
      this.$refs.editParamsFormRef.resetFields()
    },
    editParams () { // 修改参数信息
      this.$refs.editParamsFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`, {
          attr_name: this.editParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) return this.$msg.error('修改失败')
        this.$msg.success('修改成功！')
        this.getParamsData()
        this.editParamsDialogVisible = false
      })
    },
    removeParams (id) { // 点击删除按钮删除参数
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
        if (res.meta.status !== 200) return
        this.getParamsData()
        this.$msg({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$msg({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async handleInputConfirm (row) { // 下拉列表 中input框失去焦点和按下回车键触发的事件
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.saveInputValue(row)
    },
    showInput (row) { // 下拉列表中 点击按钮显示input输入框
      row.inputVisible = true
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    deleteTag (row, i) { // 移除标签
      row.attr_vals.splice(i, 1)
      this.saveInputValue(row)
    },
    async saveInputValue (row) { // 向服务器发送请求更新arr-val值
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
      })
      console.log(res)
      if (res.meta.status !== 200) return this.$msg.error('添加参数失败')
      this.$msg.success('更新数据成功')
    }

  },
  computed: {
    isBtnDisabled () { // 控制添加动态参数和添加静态属性按钮是否禁用
      if (this.selectCateKeys.length !== 3) {
        return true
      } else {
        return false
      }
    },
    cateId () { // 获取参数分类id 用于获取静态属性和动态参数
      if (this.selectCateKeys.length === 3) {
        return this.selectCateKeys[2]
      } else {
        return null
      }
    },
    titleText () { // 添加参数的 title文本
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.cate_opt {
  margin-top: 20px;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>
